class_name ResourceScheduler
extends Node

signal resource_effect_triggered(effect: ScheduledEffect, target: Node)

# 主调度器类
var scheduled_effects: Array = []  # Array[ScheduledEffect]
var resource_history: Dictionary = {}  # 记录资源变化历史
var current_battle: Node = null  # Battle instance

func _ready() -> void:
	Events.battle_started.connect(_on_battle_started)
	Events.turn_phase_changed.connect(_on_turn_phase_changed)
	Events.resource_changed.connect(_on_resource_changed)

func _on_battle_started(battle: Node) -> void:
	current_battle = battle
	resource_history.clear()
	
	# 重置所有调度效果
	for effect in scheduled_effects:
		effect.current_triggers = 0
		effect.last_trigger_turn = -1
		effect.is_active = true

func _on_turn_phase_changed(turn: int, phase: int, active_entity: Node) -> void:
	if not current_battle:
		return
	
	print("🔄 回合阶段变化: 回合 %d, 阶段 %d, 活跃实体: %s" % [turn, phase, active_entity.get_class() if active_entity else "null"])
	print("📊 当前调度效果数量: %d" % scheduled_effects.size())
	
	# 检查所有调度效果
	var effects_to_remove: Array[String] = []
	for effect in scheduled_effects:
		var target = _get_target_for_effect(effect, active_entity)
		
		print("  - %s: 已触发 %d 次, 触发类型: %d, 目标回合: %d, 目标阶段: %d" % [effect.id, effect.current_triggers, effect.trigger_type, effect.trigger_turn, effect.trigger_phase])
		
		# 对于CUSTOM目标类型，直接检查触发条件而不需要目标
		if effect.target_type == ScheduledEffect.TargetType.CUSTOM:
			if effect.can_trigger(turn, phase, null):
				print("🎯 调度效果触发: %s 作用于 %s" % [effect.id, "CUSTOM"])
				effect.trigger_effect(null)
				resource_effect_triggered.emit(effect, null)
				
				# 检查效果是否已完成（达到最大触发次数）
				if effect.max_triggers > 0 and effect.current_triggers >= effect.max_triggers:
					effects_to_remove.append(effect.id)
					print("🗑️ 效果 %s 已完成，将被移除" % effect.id)
		else:
			if target and effect.can_trigger(turn, phase, target):
				print("🎯 调度效果触发: %s 作用于 %s" % [effect.id, target.get_class()])
				effect.trigger_effect(target)
				resource_effect_triggered.emit(effect, target)
				
				# 检查效果是否已完成（达到最大触发次数）
				if effect.max_triggers > 0 and effect.current_triggers >= effect.max_triggers:
					effects_to_remove.append(effect.id)
					print("🗑️ 效果 %s 已完成，将被移除" % effect.id)
			else:
				print("  ❌ 效果 %s 无法触发: 目标=%s, can_trigger=%s" % [effect.id, "有目标" if target else "无目标", effect.can_trigger(turn, phase, target) if target else "N/A"])
	
	# 移除已完成的效果
	for effect_id in effects_to_remove:
		remove_scheduled_effect(effect_id)

func _on_resource_changed(entity: Node, resource_type: String, old_value: int, new_value: int) -> void:
	# 记录资源变化历史
	var entity_id = str(entity.get_instance_id())
	if not resource_history.has(entity_id):
		resource_history[entity_id] = {}
	
	if not resource_history[entity_id].has(resource_type):
		resource_history[entity_id][resource_type] = []
	
	resource_history[entity_id][resource_type].append({
		"turn": current_battle.current_turn if current_battle else 0,
		"old_value": old_value,
		"new_value": new_value,
		"timestamp": Time.get_unix_time_from_system()
	})

func _get_target_for_effect(effect: ScheduledEffect, active_entity: Node) -> Node:
	print("🎯 _get_target_for_effect: 为效果 %s 获取目标 (目标类型: %d)" % [effect.id, effect.target_type])
	
	var target = null
	match effect.target_type:
		ScheduledEffect.TargetType.PLAYER:
			target = current_battle.player if current_battle else null
			print("	📊 PLAYER目标类型: %s" % (target.name if target else "null"))
		ScheduledEffect.TargetType.ENEMY:
			if current_battle and current_battle.enemy_handler.get_child_count() > 0:
				target = current_battle.enemy_handler.get_child(0)
			else:
				target = null
			print("	📊 ENEMY目标类型: %s" % (target.name if target else "null"))
		ScheduledEffect.TargetType.ALL_ENEMIES:
			target = current_battle.enemy_handler if current_battle else null
			print("	📊 ALL_ENEMIES目标类型: %s" % (target.name if target else "null"))
		ScheduledEffect.TargetType.SELF:
			target = active_entity
			print("	📊 SELF目标类型: %s" % (target.name if target else "null"))
		ScheduledEffect.TargetType.CUSTOM:
			target = null  # 自定义目标类型需要额外处理
			print("	📊 CUSTOM目标类型: null")
		_:
			target = null
			print("	📊 未知目标类型: null")
	
	print("	✅ 最终目标: %s" % (target.name if target else "null"))
	return target

func add_scheduled_effect(effect: ScheduledEffect) -> void:
	scheduled_effects.append(effect)

func remove_scheduled_effect(effect_id: String) -> void:
	var new_effects: Array = []
	for effect in scheduled_effects:
		if effect.id != effect_id:
			new_effects.append(effect)
	scheduled_effects = new_effects

func get_resource_history(entity: Node, resource_type: String = "") -> Array:
	var entity_id = str(entity.get_instance_id())
	if not resource_history.has(entity_id):
		return []
	
	if resource_type.is_empty():
		return resource_history[entity_id]
	else:
		return resource_history[entity_id].get(resource_type, [])
